package com.example.demo.buessiness.department.services;


import com.example.demo.buessiness.department.model.po.Department;
import com.example.demo.buessiness.department.repository.DepartmentRepository;
import com.example.demo.buessiness.department.interfaces.IDepartmentService;
import com.example.demo.buessiness.department.model.dto.DepartmentResponse;
import com.example.demo.buessiness.department.model.dto.DepartmentRequest;


import com.example.demo.buessiness.user.model.dto.UserResponse;
import com.example.demo.buessiness.user.model.po.User;
import lombok.extern.slf4j.Slf4j;
import msa.common.exception.IDataStorageException;
import msa.common.model.DataTableVO;
import msa.common.model.PageModel;
import msa.common.model.ResultCode;
import msa.common.model.ResultModel;
import msa.common.utils.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DepartmentServiceImpl implements IDepartmentService{


    @Autowired
    DepartmentRepository defClientRepository;


    /**
     *  新增 XXX
     * @param request
     * @return ResultModel
     @Transactional(rollbackFor = IDataStorageException.class)
     @Override
     */
    @Override
    public ResultModel addDepartment(DepartmentRequest request){

      // request.setDepartment(String.valueOf(IDGenerator.getSnowflakeId()));
        try {
           Department client = defClientRepository.save (requestToPojo (request));
           if(client==null){
                return ResultModelUtils.getAddSuccessInstance(false);
           }
            return ResultModelUtils.getAddSuccessInstance (true);
        }catch (Exception e){
            log.error("添加部门异常",e);
            throw new IDataStorageException("添加部门异常",e);
        }
    }

    //查询部门名
    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public List<DepartmentResponse> findByDepartmentname(String department) {
        List<Department> clients = defClientRepository.findByDepartmentname (department);
        return pojoLisToResponseList (clients);
    }



    /**
     * 修改XXX
     * @param clientRequest
     * @return ResultModel
     */
    @Override
    public ResultModel updateDepartment(DepartmentRequest clientRequest) {
//        clientRequest.setDepartment (System.currentTimeMillis ());
        try {
            Department clients = requestToPojo (clientRequest);
            defClientRepository.save(clients);
            return ResultModelUtils.getEdiSuccessInstance (true);
        } catch (Exception e) {
            log.error ("修改部门异常",e);
            throw new IDataStorageException ("修改部门异常",e);
        }
    }


    /**
     * 删除 XX
     * @param id
     * @return ResultModel
     */
    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public ResultModel deleteDepartment(Long id) {
        try {
            defClientRepository.deleteById (id);
            return ResultModelUtils.getDelSuccessInstance (true);
        } catch (Exception e) {
            log.error ("部门异常",e);
            throw  new IDataStorageException ("删除部门异常",e);
        }
    }

    /**
     * 根据ID查询部门
     * @param id
     * @return ResultModel
     */

    @Override
    public ResultModel findDepartmentByID(Long id) {
        if(!defClientRepository.existsById(id)){
            return ResultModelUtils.getFailInstance(ResultCode.PARAM_NULL.toString(),"该部门不存在");
        }
        Department client=defClientRepository.findById(id).get();
        return ResultModelUtils.getSuccessInstance(pojoToResponse(client));
    }

    /**
     * 根据name查询部门
     * @param department
     * @return ResultModel
     */



    /**
     *  获取所有XX
     * @return List<DepartmentResponse> XXX返回实体集合
     */
    @Override
    public List<DepartmentResponse> findAll() {
        List<Department> clients = defClientRepository.findAllByOrderByIdAsc();
        return pojoLisToResponseList (clients);
    }

    /**
     * 根据name查询部门
     * @param department
     * @return ResultModel
     */
    @Override
    public ResultModel findDepartmentByName(String department) {
        if(StringUtils.isEmpty(department)){
            return ResultModelUtils.getFailInstance(ResultCode.PARAM_NULL.toString(),"该部门不存在");
        }
        Department client=defClientRepository.findByDepartment(department);
        System.out.println(client);
        return ResultModelUtils.getSuccessInstance(pojoToResponse(client));
    }


    /**
     *  分页
     * @return DataTableVO
     */
    @Override
    public DataTableVO page(PageModel pageModel) {
        DepartmentRequest request=(DepartmentRequest)pageModel.getSearchData();
        Page<Department> page=defClientRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates=new ArrayList<>();
            if (request.getCompany()!=null){
                predicates.add(criteriaBuilder.equal(root.get("company").as(String.class),request.getCompany()));
            }return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).orderBy (criteriaBuilder.asc (root.get ("time"))).getRestriction();
        },pageModel.getPageRequestInstance ());
        DataTableVO dataTableVO =  DataTableConverter.convert(page);
        List<Department> clients = page.getContent ();
        dataTableVO.setData (pojoLisToResponseList (clients));
        return dataTableVO;

    }



    /**
     *  XX数据接收实体转换为数据pojo类
     * @param departmentRequest XX数据接收实体
     * @return client XX数据pojo类
     */
    @Override
    public Department requestToPojo(DepartmentRequest departmentRequest) {
        Department client = new Department ();
        BeanUtils.copyProperties (departmentRequest,client);
        client.setId (Long.parseLong (departmentRequest.getId ()));
/*        if (departmentRequest.getDepartment ()!=null) {
            client.setDepartment (DateUtils.convertTimeToDate (departmentRequest.getDepartment()));
        }*/
        return client;
    }


    /**
     *  XX数据接收实体集合转换为数据pojo类集合
     * @param list XX数据接收实体
     * @return clients XX数据pojo类集合
     */
    @Override
    public List requestListToPojoList(List<DepartmentRequest> list) {
        if (CollectionUtils.isEmpty (list)) {
            return null;
        }
        List<Department> clients = new ArrayList<> ();
        list.stream ().filter (clientRequest -> clientRequest!=null).forEach (clientRequest -> {
            clients.add (requestToPojo (clientRequest));
        });
        return clients;
    }


    /**
     *  XX数据pojo转换为数据返回response
     * @param o XX数据pojo类
     * @return clientResponse XX数据pojo类
     */
    @Override
    public DepartmentResponse pojoToResponse(Object o) {
        DepartmentResponse clientResponse = new DepartmentResponse ();
        Department client =(Department)o;
        BeanUtils.copyProperties (client,clientResponse);
        clientResponse.setId (String.valueOf (client.getId ()));
        return clientResponse;
    }

    @Override
    public List<DepartmentResponse> pojoLisToResponseList(List list) {
        if (CollectionUtils.isEmpty (list)) {
            return new ArrayList<> ();
        }
        List<DepartmentResponse> responses = new ArrayList<> ();
        list.stream ().filter (client->client!=null).forEach (client->{
            responses.add (pojoToResponse (client));
        });
        return responses;
    }
}
